package 
{
	import com.adobe.serialization.json.JSON;
	import com.giantflyingsaucer.Base64;
	import controller.Const;
	import controller.GameController;
	import controller.RequestController;
	import flash.display.Bitmap;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	import model.GameData;
	import model.MyData;
	import sound.SoundManager;
	import util.Stats;
	import view.BackGround;
	import view.Betting;
	import view.DialLucky;
	import view.history.HistoryBet;
	import view.loading.LoadingGame;
	import view.LoginScreen;
	import view.popup.NoticePopup;

	import view.TopPlayers;

	import view.ShowResult;

	
	import view.PreLoader;
	import view.Result;
	
	/**
	 * ...
	 * @author bimkute
	 * 
	 */
	public class Main extends Sprite 
	{
		[Embed(source="../lib/image/bg.jpg")]
		private var bgClass:Class;
		private var bg:Bitmap;
		private var _result:Result;
		private var _preLoader:PreLoader;
		private var _background:BackGround;
		private var _betting:Betting;
		private var _dialLucky:DialLucky;
		private var _notice:NoticePopup;
		private var _login:LoginScreen;
		private var _stats:Stats;
		
		
		//add BackGround
		private var _backGround:BackGround;
		private var _showResult:ShowResult;
		static private var instance:Main;
		private var _loading:LoadingGame;
		private var _history:HistoryBet;
		private var _arrCountUserBetting:Array = [];
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			//GameController.getInstance().loadSwf("http://www.daodudu.com/bimkute/tlmnTest/loading.swf", "loading", true);
			//GameController.getInstance().loadSwf("../lib/image/loading.swf", "loading", true);
			//GameController.getInstance().loadSwf("http://thanhha-jsc.com/ngutruonghuahen/lib/image/loading.swf", "loading", true);
			GameController.getInstance().loadSwf("lib/image/loading.swf", "loading", true);
			//GameController.getInstance().loadSwf("http://nhiteqs.byethost5.com/swf/loading.swf", "loading", true);
			GameController.getInstance().addEventListener("loadingComplete", onLoadingComplete);
			
			var sp:Sprite = new Sprite();
			sp.graphics.beginFill(0x123456, 1);
			sp.graphics.drawRect(0, 0, 1440, 900);
			sp.graphics.endFill();
			addChild(sp);
			mask = sp;
			
			
			bg = new bgClass();
			addChild(bg);
			

			addSound();
			//noticeGame();
			
			/*_stats = new Stats();
			addChild(_stats);
			_stats.x = 150;
			_stats.y = 150;
			setChildIndex(_stats, numChildren - 1);*/
		}
		

		private function addSound():void 
		{
			//var arrSound:Array = [	"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/Theme_01.mp3", 
									//"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/Theme_02.mp3", 
									//"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/Theme_03.mp3",
									//"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/Click_1.mp3", 
									//"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/Click_2.mp3", 
									//"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/Click_3.mp3",
									//"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/CheoThuyen.mp3", 
									//"http://thanhha-jsc.com/ngutruonghuahen/lib/sound/Keoca.mp3"];
									
			
			var arrSound:Array = [	"lib/sound/Theme_01.mp3", 
									"lib/sound/Theme_02.mp3", 
									"lib/sound/Theme_03.mp3",
									"lib/sound/Click_1.mp3", 
									"lib/sound/Click_2.mp3", 
									"lib/sound/Click_3.mp3",
									"lib/sound/CheoThuyen.mp3", 
									"lib/sound/Keoca.mp3"];
			var arrSoundName:Array = [	"Bg1", "Bg2", "Bg3", "Click1", "Click2","Click3", "CheoThuyen","Keoca"];

			for (var i:int = 0; i < arrSound.length; i++) 
			{
				var tempSound:Sound = new Sound();
				tempSound.load(new URLRequest(arrSound[i]));
				
				SoundManager.getInstance().registerSound(arrSoundName[i], tempSound);
			}
  
		}
		

		public function showNoticePopup(str:String):void 
		{
			if (_notice) 
			{
				_notice.addText(str);
				_notice.visible = true;
				setChildIndex(_notice, this.numChildren - 1);
				_notice.addText(str);
			}
			
		}
		
		private function onLoadingComplete(e:Event):void 
		{
			GameController.getInstance().removeEventListener("loadingComplete", onLoadingComplete);
			
			addPreLoader();
			addLoadingGame();
			
			getFlashVar();
		}
		
		private function addLoadingGame():void 
		{
			if (!_loading)
			{
				_loading = new LoadingGame();
				addChild(_loading);
				_loading.x = (stage.stageWidth - _loading.width) / 2 + 20;
				_loading.y = (stage.stageHeight - _loading.height) / 2 + 100;
			}
			
			GameData.getInstance().addEventListener("enableLoading", enableLoading)
			GameData.getInstance().addEventListener("visibleLoading", visibleLoading)
			_loading.visible = false;
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
			//
		}
		
		private function visibleLoading(e:Event):void 
		{
			_loading.visible = false;
		}
		
		private function enableLoading(e:Event):void 
		{
			_loading.visible = true;
		}
		
		private function addPreLoader():void 
		{
			if (!_preLoader) 
			{
				_preLoader = new PreLoader();
				addChild(_preLoader);
				_preLoader.x = (stage.stageWidth - _preLoader.width) / 2;
				_preLoader.y = 0;
			}
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function getFlashVar():void 
		{
			/*var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
			trace(paramObj)
			if (paramObj.loginData) 
			{
				var str:String = Base64.decode(paramObj.loginData);
				trace("teststsstsrarsa: ", str)
				if (str == "Bạn chưa đăng nhập") 
				{
					//showNoticePopup("Bạn chưa đăng nhập, xin vui lòng đăng nhập trước khi chơi game");
				}
				else 
				{
					var obj:Object = JSON.decode(str);
					MyData.getInstance().myName = obj.name;
					MyData.getInstance().myMoney = obj.money;
				}
			}
			else 
			{
				getInfoUser();
			}*/
			
			//getInfoUser();
			
			_login = new LoginScreen();
			addChild(_login);
			_login.addEventListener("login", onLogin);
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function onLogin(e:Event):void 
		{
			
			
			MyData.getInstance().myName = _login._userName;
			MyData.getInstance().myMoney = 100000;
			
			_login.removeEventListener("login", onLogin);
			removeChild(_login);
			_login = null;
			
			addEventListener(Event.ENTER_FRAME, changeSeekLoading);
			for (var i:int = 0; i < GameData.getInstance().arrLoad.length; i++) 
			{
				GameController.getInstance().loadSwf(GameData.getInstance().arrLoad[i][0], 
														GameData.getInstance().arrLoad[i][1]);
			}
			
			GameController.getInstance().addEventListener("loadComplete", onCompleteLoadSwf);
		}
		
		private function getInfoUser():void 
		{
			var urlReg:URLRequest = new URLRequest("http://www.daodudu.com/api/logininfo");
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onCompleteLoadUserInfo);
			loader.load(urlReg);
			
			
		}
		
		private function onCompleteLoadUserInfo(e:Event):void 
		{
			MyData.getInstance().myName = "test2";;
			MyData.getInstance().myMoney = 100000;
			/*if (e.target.data == "Bạn chưa đăng nhập") 
			{
				//showNoticePopup("Bạn chưa đăng nhập, xin vui lòng đăng nhập trước khi chơi game");
			}
			else 
			{
				var obj:Object = JSON.decode(e.target.data);
				MyData.getInstance().myName = obj.name;
				MyData.getInstance().myMoney = obj.money;
				MyData.getInstance().myMoney = 100000;
				
				addEventListener(Event.ENTER_FRAME, changeSeekLoading);
				for (var i:int = 0; i < GameData.getInstance().arrLoad.length; i++) 
				{
					GameController.getInstance().loadSwf(GameData.getInstance().arrLoad[i][0], 
															GameData.getInstance().arrLoad[i][1]);
				}
				
				GameController.getInstance().addEventListener("loadComplete", onCompleteLoadSwf);
			}*/
			addEventListener(Event.ENTER_FRAME, changeSeekLoading);
			for (var i:int = 0; i < GameData.getInstance().arrLoad.length; i++) 
			{
				GameController.getInstance().loadSwf(GameData.getInstance().arrLoad[i][0], 
														GameData.getInstance().arrLoad[i][1]);
			}
			
			GameController.getInstance().addEventListener("loadComplete", onCompleteLoadSwf);
		}
		
		private function changeSeekLoading(e:Event):void 
		{
			
			_preLoader.changeSeek(GameController.getInstance().percent);
		}
		
		private function onCompleteLoadSwf(e:Event):void 
		{
			removeEventListener(Event.ENTER_FRAME, changeSeekLoading);
			
			/*var timer:Timer = new Timer(1000, 3);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, onAddData);
			timer.start();*/
			getInfoMatch();
			
			addBgAndBetting();
			
			
		}
		
		private function getInfoMatch():void 
		{
			
			RequestController.getInstance().getInfo();
			RequestController.getInstance().addEventListener("call_error", onSendGetInfoAgain);
			RequestController.getInstance().addEventListener("call_complete", onSendGetInfoSuccess);
			
		}
		
		private function onSendGetInfoSuccess(e:Event):void 
		{
			RequestController.getInstance().removeEventListener("call_error", onSendGetInfoAgain);
			RequestController.getInstance().removeEventListener("call_complete", onSendGetInfoSuccess);
			
		}
		
		private function onSendGetInfoAgain(e:Event):void 
		{
			RequestController.getInstance().removeEventListener("call_error", onSendGetInfoAgain);
			RequestController.getInstance().removeEventListener("call_complete", onSendGetInfoSuccess);
			getInfoMatch();
		}
		
		private function onAddData(e:TimerEvent):void 
		{
			var ran:int;
			var arr:Array = [];
			
			GameData.getInstance().multi = arr;
			
			ran = Math.ceil(Math.random() * 140);
			GameData.getInstance().timeRemain = ran;
			//dữ liệu này gồm mảng là các số trúng thưởng ở mỗi bảng 30, 20, 5%
			//bao gồm gọi lên 3 lần request
			
			GameData.getInstance().arrNumberDialing = [5, 3, 2];
		}
		
		private function addBgAndBetting():void 
		{
			addBackGround();
			
			//addDialing();
			//addShowResult();
			addBetting();
			
			noticeGame();
			RequestController.getInstance().addEventListener("getResultComplete", onGetResultSuccess);
			RequestController.getInstance().addEventListener("getHistoryComplete", onGetHistorySuccess);
			//GameData.getInstance().addEventListener("historyTransaction", showHistoryTransaction);
		}
		
		private function onGetHistorySuccess(e:Event):void 
		{
			//RequestController.getInstance().removeEventListener("getHistoryComplete", onGetHistorySuccess);
			trace("GameData.getInstance().arrTransaction", GameData.getInstance().arrTransaction)
			if (_history)
			{
				_history.showInfo(GameData.getInstance().arrTransaction);
			}
		}
		
		//private function showHistoryTransaction(e:Event):void 
		//{
			//trace("GameData.getInstance().arrTransaction", GameData.getInstance().arrTransaction)
			//if (_history)
			//{
				//_history.showInfo(GameData.getInstance().arrTransaction);
			//}
			//
		//}
		
		private function onGetResultSuccess(e:Event):void 
		{
			RequestController.getInstance().removeEventListener("getResultComplete", onGetResultSuccess);
			addShowResult();
		}
		
		private function addShowResult():void 
		{
			_background.visibleBoatmen();
			
			//****stopSound*******
			_background.stopSoundBg();
			
			if (_betting)
			{
				_betting.removeAllEvent();
				_betting.removeEventListener("addHistory", addHistory)
				GameData.getInstance().removeEventListener("multi", onGetMultiData);
				GameData.getInstance().removeEventListener("timeRemain", onTimeRemainData);
				//GameData.getInstance().removeEventListener("callResult", onShowKetQua);
				_betting.removeEventListener("showNotice", showNotice);
				_betting.removeEventListener("sendDataSuccess", bettingSuccess);
				_betting.removeEventListener("not_enough_money", notEnoughMoney);
				//removeChild(_betting);
				//_betting = null;
			}
			if (_history)
			{
				_history.removeAllEvent();
				removeChild(_history);
				_history = null;
			}
			if (!_showResult)
			{
				//trace("GameData.getInstance().timeRemain", GameData.getInstance().timeRemain)
				_showResult = new ShowResult();
				addChild(_showResult);
				if (GameData.getInstance().multi[Const.FACTOR])
				{
					_arrCountUserBetting = GameData.getInstance().multi[Const.FACTOR].split(",");
				}
				
				//_showResult.getUserBetting(_arrCountUserBetting, MyData.getInstance()._arrBetting);
				
				//_showResult.addEventListener("completeKeoLuoi", showResult)
				_showResult.addEventListener("completeQuangLuoi", showResult)
				_showResult.addEventListener("showMoneyUser", addResult);
			}
			
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function showResult(e:Event):void 
		{
			trace("GameData.getInstance().result", GameData.getInstance().result)
			_showResult.showResult(GameData.getInstance().result);
		}
		
		
		//private function showResult(e:Event):void 
		//{
			//_showResult.showResult(GameData.getInstance().result);
		//}
		
		private function completeKeoLuoi(e:Event):void 
		{
			//GameData.getInstance().arrUserBetting = [[1, 300], [2, 400], [3, 500], [4, 600]];
			//GameData.getInstance().arrResult = [[1, 3], [2, 4], [3, 5], [4, 6]];
			//GameData.getInstance().arrTreasure = [[1, 3]];
			//GameData.getInstance().addEventListener("showUserBetting", showUserBetting)
			//
			//_showResult.getResult(GameData.getInstance().arrResult);
			//_showResult.getUserBetting(GameData.getInstance().arrUserBetting);
			//_showResult.getTreasure(GameData.getInstance().arrTreasure);
		}
		
		//private function showUserBetting(e:Event):void 
		//{
			//_showResult.getUserBetting(GameData.getInstance().arrUserBetting);
			//_showResult.getTreasure(GameData.getInstance().arrTreasure);
		//}
		
		
		private function addResult(e:Event):void 
		{
			_showResult.removeEventListener("showMoneyUser", addResult);
			if (!_result)
			{
				trace("GameData.getInstance().totalWin", GameData.getInstance().totalWin)
				
				
				if (GameData.getInstance().totalWin >= 0)
				{
					_result = new Result(true);
					addChild(_result);
					
				}
				else
				{
					_result = new Result(false);
					addChild(_result);
					//_result.addEventListener("close", closeProject);
				}
				
				_result.addEventListener("close", closeProject);
				
			}
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function closeProject(e:Event):void 
		{
			_result.removeEventListener("close", closeProject);
			RequestController.getInstance().removeEventListener("getResultComplete", onGetResultSuccess);
			RequestController.getInstance().removeEventListener("getHistoryComplete", onGetHistorySuccess);
			if (_showResult)
			{
				_showResult.removeEventListener("completeQuangLuoi", showResult)
				_showResult.removeEventListener("showMoneyUser", addResult);
				_showResult.removeAllEvent();
				removeChild(_showResult);
				_showResult = null;
			}
			if (_result)
			{
				_result.removeAllEvent();
				removeChild(_result);
				_result = null;
			}
			if (_betting)
			{
				_betting.removePopUp();
				_betting.removeAllEvent();
				GameData.getInstance().removeEventListener("multi", onGetMultiData);
				GameData.getInstance().removeEventListener("timeRemain", onTimeRemainData);
				//GameData.getInstance().removeEventListener("callResult", onShowKetQua);
				_betting.removeEventListener("showNotice", showNotice);
				_betting.removeEventListener("sendDataSuccess", bettingSuccess);
				_betting.removeEventListener("not_enough_money", notEnoughMoney);
				_betting.removeEventListener("addHistory", addHistory)
				removeChild(_betting);
				_betting = null;
			}
			if (_background)
			{
				_background.removeAllEvent();
				removeChild(_background);
				_background = null;
			}
			if (_preLoader)
			{
				removeChild(_preLoader);
				_preLoader = null;
			}
			
			if (bg)
			{
				removeChild(bg);
				bg = null;
			}
			if (_notice)
			{
				_notice.removeAllEvent();
				removeChild(_notice);
				_notice = null;
			}
			if (_history)
			{
				_history.removeAllEvent();
				removeChild(_history);
				_history = null;
			}
			var i:int
			
			if (_arrCountUserBetting && _arrCountUserBetting.length > 0)
			{
				for (i = 0; i < _arrCountUserBetting.length; i++) 
				{
					_arrCountUserBetting[i] = null;
				}
			}
			
			if (MyData.getInstance()._arrBetting && MyData.getInstance()._arrBetting.length > 0)
			{
				for (i = 0; i < MyData.getInstance()._arrBetting.length; i++) 
				{
					MyData.getInstance()._arrBetting[i] = null;
				}
			}
			
			_arrCountUserBetting = [];
			GameData.getInstance().totalWin = 0;
			MyData.getInstance()._arrBetting = [];
			MyData.getInstance()._getDataMatchComplete = false;
			MyData.getInstance().canStartGame = true;
			
			_loading.visible = true;
			setChildIndex(_loading, numChildren - 1);
			
			getInfoMatch();
			
			addBgAndBetting();
		}
		
		private function onCompleteSendRequest(e:TimerEvent):void 
		{
			
		}
		
		private function addDialing():void 
		{
			if (!_dialLucky)
			{
				_dialLucky = new DialLucky();
				addChild(_dialLucky);
				GameData.getInstance().addEventListener("numberDialing", onDialing);
			}
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function onDialing(e:Event):void 
		{
			
			if (_dialLucky)
			{
				_dialLucky.getDialing(GameData.getInstance().arrNumberDialing);
			}
			
		}
		
		
		
		private function addBetting():void 
		{
			if (!_betting) 
			{
				_betting = new Betting(MyData.getInstance().myMoney);
				addChild(_betting);
				
				GameData.getInstance().addEventListener("multi", onGetMultiData);
				GameData.getInstance().addEventListener("timeRemain", onTimeRemainData);
				//GameData.getInstance().addEventListener("callResult", onShowKetQua);
				_betting.addEventListener("showNotice", showNotice);
				_betting.addEventListener("sendDataSuccess", bettingSuccess);
				_betting.addEventListener("not_enough_money", notEnoughMoney);
				_betting.addEventListener("addHistory", addHistory)
				//RequestController.getInstance().addEventListener("getResultComplete", onGetResultSuccess);
			}
			setChildIndex(_loading, numChildren - 1);
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function addHistory(e:Event):void 
		{
			if (!_history)
			{
				_history = new HistoryBet();
				addChild(_history);
				_history.addEventListener("closeHistory", closeHistory)
			}
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function closeHistory(e:Event):void 
		{
			if (_history)
			{
				_history.removeAllEvent();
				removeChild(_history);
				_history = null;
			}
		}
		
		private function notEnoughMoney(e:Event):void 
		{
			showNoticePopup(Const.TEXT_BUY_CARD);
		}
		
		private function bettingSuccess(e:Event):void 
		{
			showNoticePopup(Const.TEXT_BETTING_SUCCESS);
		}
		
		private function showNotice(e:Event):void 
		{
			
			showNoticePopup(Const.TEXT_BETTING)
		}
		
		//private function onShowKetQua(e:Event):void 
		//{
			//GameData.getInstance().removeEventListener("callResult", onShowKetQua);
			//addShowResult();
		//}
		
		private function onTimeRemainData(e:Event):void 
		{
			if (_showResult)
			{
				_showResult.removeAllEvent();
				removeChild(_showResult);
				_showResult = null;
			}
			if (_betting) 
			{
				_betting.timeRemain(GameData.getInstance().timeRemain);
			}
			if (_background)
			{
				_background.moveThuyen(GameData.getInstance().timeRemain);
			}
		}
		
		private function onGetMultiData(e:Event):void 
		{
			if (_betting) 
			{
				_betting.getMulti(GameData.getInstance().multi[Const.FACTOR]);
			}
		}
		
		private function addBackGround():void 
		{
			if (!_background)
			{
				_background = new BackGround();
				addChild(_background);
			}
			setChildIndex(_loading, numChildren - 1);
			if (_stats) 
			{
				setChildIndex(_stats, numChildren - 1);
			}
		}
		
		private function noticeGame():void 
		{
			if (!_notice) 
			{
				_notice = new NoticePopup();
				addChild(_notice);
				//_noticePopup.x = (1024 - _noticePopup.width) / 2;
				//_noticePopup.y = (600 - _noticePopup.height) / 2;
				
				
				_notice.visible = false;
				_notice.addEventListener("close popup", onClosePopup);
				_notice.addEventListener("agreeBetting", onAgreeBetting);
			}
		}
		
		private function onAgreeBetting(e:Event):void 
		{
			onClosePopup(null);
			if (_betting) 
			{
				_betting.agreeSendData();
			}
		}
		
		private function onClosePopup(e:Event):void 
		{ 
			
			_notice.visible = false;
		}
	}
	
}